<template>
  <a-modal
    v-model:open="visible"
    :title="modalTitle"
    width="900px"
    :footer="null"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
      class="product-form"
    >
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="section-title">基本信息</h3>
        <div class="form-row">
          <div class="form-column">
            <a-form-item label="名称" name="name" required>
              <a-input
                v-model:value="formData.name"
                placeholder="请输入商品名称"
                size="large"
              />
            </a-form-item>
            <a-form-item label="分类" name="category" required>
              <a-select
                v-model:value="formData.category"
                placeholder="请选择分类"
                size="large"
              >
                <a-select-option value="internal">内科用药</a-select-option>
                <a-select-option value="external">外驱</a-select-option>
                <a-select-option value="internal-deworming"
                  >内驱</a-select-option
                >
                <a-select-option value="package">套餐</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="品牌" name="brand">
              <a-input
                v-model:value="formData.brand"
                placeholder="请输入品牌"
                size="large"
              />
            </a-form-item>
            <a-form-item label="厂家" name="manufacturer">
              <a-input
                v-model:value="formData.manufacturer"
                placeholder="请输入厂家"
                size="large"
              />
            </a-form-item>
            <a-form-item label="单位" name="unit">
              <a-input
                v-model:value="formData.unit"
                placeholder="请输入单位"
                size="large"
              />
            </a-form-item>
            <a-form-item label="规格" name="specification">
              <a-input
                v-model:value="formData.specification"
                placeholder="请输入规格"
                size="large"
              />
            </a-form-item>
          </div>
          <div class="form-column">
            <a-form-item label="别名" name="alias">
              <div class="alias-container">
                <a-checkbox
                  v-model:checked="formData.useAlias"
                  style="margin-right: 8px"
                >
                  别名
                </a-checkbox>
                <a-form-item-rest>
                  <a-input
                    v-model:value="formData.alias"
                    placeholder="打印、给用户显示别名"
                    size="large"
                    :disabled="!formData.useAlias"
                  />
                </a-form-item-rest>
              </div>
            </a-form-item>
            <a-form-item label="编号" name="code">
              <a-input
                v-model:value="formData.code"
                placeholder="请输入编号"
                size="large"
              />
            </a-form-item>
            <a-form-item label="条码" name="barcode">
              <a-input
                v-model:value="formData.barcode"
                placeholder="请输入条码"
                size="large"
              />
            </a-form-item>
            <a-form-item label="拼音搜索" name="pinyin">
              <a-input
                v-model:value="formData.pinyin"
                placeholder="请输入拼音"
                size="large"
              />
            </a-form-item>
            <a-form-item label="计算库存" name="calculateInventory">
              <div class="checkbox-container">
                <a-checkbox
                  v-model:checked="formData.calculateInventory"
                  style="margin-right: 8px"
                >
                  计算库存
                </a-checkbox>
                <a-form-item-rest>
                  <span class="help-text"
                    >(库存下限: {{ formData.inventoryLimit }})</span
                  >
                  <a-tooltip title="是否计算库存">
                    <a-icon type="question-circle" class="help-icon" />
                  </a-tooltip>
                </a-form-item-rest>
              </div>
            </a-form-item>
          </div>
        </div>

        <!-- 其他设置 -->
        <div class="other-settings">
          <a-form-item>
            <a-space>
              <a-checkbox v-model:checked="formData.participateDiscount">
                参与打折
              </a-checkbox>
              <a-checkbox v-model:checked="formData.hasBatchNumber">
                有批号
              </a-checkbox>
              <a-checkbox v-model:checked="formData.recommended">
                推荐标记
                <a-icon
                  type="check-circle"
                  style="margin-left: 4px; color: #52c41a"
                />
              </a-checkbox>
            </a-space>
          </a-form-item>
        </div>
      </div>

      <!-- 详细信息标签页 -->
      <div class="form-section">
        <a-tabs v-model:activeKey="activeTab" class="detail-tabs">
          <!-- 价格标签页 -->
          <a-tab-pane key="price" tab="价格">
            <div class="price-form">
              <div class="form-row">
                <div class="form-column">
                  <a-form-item label="售价" name="unitPrice">
                    <a-input-number
                      v-model:value="formData.unitPrice"
                      placeholder="请输入售价"
                      size="large"
                      style="width: 100%"
                      :precision="2"
                      :min="0"
                    />
                  </a-form-item>
                  <a-form-item label="最低售价" name="minimumPrice">
                    <a-input-number
                      v-model:value="formData.minimumPrice"
                      placeholder="请输入最低售价"
                      size="large"
                      style="width: 100%"
                      :precision="2"
                      :min="0"
                    />
                  </a-form-item>
                  <a-form-item label="成本价" name="costPrice">
                    <a-input-number
                      v-model:value="formData.costPrice"
                      placeholder="请输入成本价"
                      size="large"
                      style="width: 100%"
                      :precision="2"
                      :min="0"
                    />
                  </a-form-item>
                </div>
                <div class="form-column">
                  <a-form-item label="出库批发价" name="wholesalePrice">
                    <a-input-number
                      v-model:value="formData.wholesalePrice"
                      placeholder="请输入批发价"
                      size="large"
                      style="width: 100%"
                      :precision="2"
                      :min="0"
                    />
                  </a-form-item>
                  <a-form-item label="会员价" name="memberPrice">
                    <div class="member-price-container">
                      <a-checkbox
                        v-model:checked="formData.useMemberPrice"
                        style="margin-right: 8px"
                      >
                        使用会员价
                      </a-checkbox>
                      <a-form-item-rest>
                        <a-input-number
                          v-model:value="formData.memberPrice"
                          placeholder="请输入会员价"
                          size="large"
                          style="width: 100%"
                          :precision="2"
                          :min="0"
                          :disabled="!formData.useMemberPrice"
                        />
                      </a-form-item-rest>
                    </div>
                    <a-form-item-rest>
                      <div class="help-text">
                        会员卡用户将以此价格最终结算,而非会员卡原有折扣
                      </div>
                    </a-form-item-rest>
                  </a-form-item>
                </div>
              </div>
            </div>
          </a-tab-pane>

          <!-- 用法标签页 -->
          <a-tab-pane key="usage" tab="用法">
            <div class="usage-form">
              <div class="usage-description">主要用于处方药计算用量使用</div>
              <a-form-item label="用法设置" name="usageSetting">
                <div class="usage-setting-container">
                  <a-select
                    v-model:value="formData.usageType"
                    placeholder="请选择用法类型"
                    style="width: 200px"
                  >
                    <a-select-option value="oral">口服</a-select-option>
                    <a-select-option value="injection">注射</a-select-option>
                    <a-select-option value="external">外用</a-select-option>
                  </a-select>
                  <a-form-item-rest>
                    <a-button type="primary">设置处方用法</a-button>
                  </a-form-item-rest>
                </div>
              </a-form-item>

              <a-form-item label="用量设置" name="dosageSetting">
                <div class="dosage-settings">
                  <div class="dosage-item">
                    <span class="dosage-label">猫类—每千克消耗:</span>
                    <a-input-number
                      v-model:value="formData.catDosage"
                      placeholder="0.00"
                      style="width: 100px"
                      :precision="2"
                      :min="0"
                    />
                    <a-form-item-rest>
                      <a-button size="small">复制</a-button>
                      <a-button size="small">粘贴</a-button>
                    </a-form-item-rest>
                  </div>
                  <div class="dosage-item">
                    <span class="dosage-label">狗类—每千克消耗:</span>
                    <a-input-number
                      v-model:value="formData.dogDosage"
                      placeholder="0.00"
                      style="width: 100px"
                      :precision="2"
                      :min="0"
                    />
                    <a-form-item-rest>
                      <a-button size="small">复制</a-button>
                      <a-button size="small">粘贴</a-button>
                    </a-form-item-rest>
                  </div>
                  <div class="dosage-item">
                    <span class="dosage-label">其它类—每千克消耗:</span>
                    <a-input-number
                      v-model:value="formData.otherDosage"
                      placeholder="0.00"
                      style="width: 100px"
                      :precision="2"
                      :min="0"
                    />
                    <a-form-item-rest>
                      <a-button size="small">复制</a-button>
                      <a-button size="small">粘贴</a-button>
                    </a-form-item-rest>
                  </div>
                </div>
                <a-form-item-rest>
                  <div class="help-text">
                    用量设置后,系统将根据宠物种类和病历测量的体重自动计算出实际处方用量
                  </div>
                </a-form-item-rest>
              </a-form-item>
            </div>
          </a-tab-pane>

          <!-- 积分兑换标签页 -->
          <a-tab-pane key="points" tab="积分兑换">
            <div class="points-form">
              <a-form-item label="积分兑换" name="pointsExchange">
                <a-checkbox v-model:checked="formData.enablePointsExchange">
                  启用积分兑换
                </a-checkbox>
              </a-form-item>
              <a-form-item label="兑换积分" name="exchangePoints">
                <a-input-number
                  v-model:value="formData.exchangePoints"
                  placeholder="请输入兑换所需积分"
                  style="width: 200px"
                  :precision="0"
                  :min="0"
                  :disabled="!formData.enablePointsExchange"
                />
              </a-form-item>
            </div>
          </a-tab-pane>

          <!-- 说明标签页 -->
          <a-tab-pane key="description" tab="说明">
            <div class="description-form">
              <a-form-item label="商品说明" name="description">
                <a-textarea
                  v-model:value="formData.description"
                  placeholder="请输入商品说明"
                  :rows="6"
                />
              </a-form-item>
            </div>
          </a-tab-pane>

          <!-- 有效期标签页 -->
          <a-tab-pane key="validity" tab="有效期">
            <div class="validity-form">
              <a-form-item label="有效期" name="validityPeriod">
                <a-date-picker
                  v-model:value="formData.validityPeriod"
                  placeholder="请选择有效期"
                  style="width: 200px"
                />
              </a-form-item>
              <a-form-item label="保质期天数" name="shelfLife">
                <a-input-number
                  v-model:value="formData.shelfLife"
                  placeholder="请输入保质期天数"
                  style="width: 200px"
                  :precision="0"
                  :min="0"
                />
              </a-form-item>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-form>

    <!-- 操作按钮 -->
    <div class="modal-footer">
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="saving" @click="handleSave">
          保存
        </a-button>
      </a-space>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import { message } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import dayjs from 'dayjs';

// 定义props
interface Props {
  visible: boolean;
  product?: any;
  primaryCategory: string;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  product: null,
  primaryCategory: 'registration',
});

// 定义emits
const emit = defineEmits<{
  'update:visible': [value: boolean];
  save: [product: any]
}>();

// 响应式数据
const formRef = ref<FormInstance>();
const saving = ref(false);
const activeTab = ref('price');

// 表单数据
const formData = reactive({
  name: '',
  category: '',
  brand: '',
  manufacturer: '',
  unit: '',
  specification: '',
  useAlias: false,
  alias: '',
  code: '',
  barcode: '',
  pinyin: '',
  calculateInventory: false,
  inventoryLimit: 0,
  participateDiscount: false,
  hasBatchNumber: false,
  recommended: false,
  unitPrice: 0,
  minimumPrice: 0,
  costPrice: 0,
  wholesalePrice: 0,
  useMemberPrice: false,
  memberPrice: 0,
  usageType: '',
  catDosage: 0,
  dogDosage: 0,
  otherDosage: 0,
  enablePointsExchange: false,
  exchangePoints: 0,
  description: '',
  validityPeriod: null,
  shelfLife: 0,
});

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入商品名称',trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类',trigger: 'change' }],
};

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const modalTitle = computed(() => {
  return props.product ? `修改项目(${props.product.name})` : '添加项目';
});

// 监听props变化，初始化表单数据
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible) {
      if (props.product) {
        // 编辑模式，填充现有数据
        Object.assign(formData, {
          ...props.product,
          validityPeriod: props.product.validityPeriod
            ? dayjs(props.product.validityPeriod)
            : null,
        });
      } else {
        // 新增模式，重置表单
        resetForm();
      }
    }
  },
);

// 方法
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    category: '',
    brand: '',
    manufacturer: '',
    unit: '',
    specification: '',
    useAlias: false,
    alias: '',
    code: '',
    barcode: '',
    pinyin: '',
    calculateInventory: false,
    inventoryLimit: 0,
    participateDiscount: false,
    hasBatchNumber: false,
    recommended: false,
    unitPrice: 0,
    minimumPrice: 0,
    costPrice: 0,
    wholesalePrice: 0,
    useMemberPrice: false,
    memberPrice: 0,
    usageType: '',
    catDosage: 0,
    dogDosage: 0,
    otherDosage: 0,
    enablePointsExchange: false,
    exchangePoints: 0,
    description: '',
    validityPeriod: null,
    shelfLife: 0,
  });
};

const handleSave = async () => {
  try {
    await formRef.value?.validate();
    saving.value = true;

    // 模拟保存请求
    await new Promise((resolve) => setTimeout(resolve, 1000));

    const productData = {
      ...formData,
      validityPeriod: formData.validityPeriod
        ? formData.validityPeriod.format('YYYY-MM-DD')
        : '',
      id: props.product?.id,
    };

    emit('save', productData);
    message.success('保存成功');
    visible.value = false;
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    saving.value = false;
  }
};

const handleCancel = () => {
  visible.value = false;
};
</script>

<style scoped>
/* 响应式设计 */
@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 16px;
  }

  .usage-setting-container {
    flex-direction: column;
    align-items: flex-start;
  }

  .dosage-item {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }

  .dosage-label {
    min-width: auto;
  }
}

.product-form {
  max-height: 70vh;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 24px;
}

.section-title {
  padding-bottom: 8px;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid #e8e8e8;
}

.form-row {
  display: flex;
  gap: 24px;
}

.form-column {
  flex: 1;
  min-width: 0;
}

.alias-container {
  display: flex;
  gap: 8px;
  align-items: center;
}

.checkbox-container {
  display: flex;
  gap: 8px;
  align-items: center;
}

.help-text {
  margin-top: 4px;
  font-size: 12px;
  color: #666;
}

.help-icon {
  color: #1890ff;
  cursor: pointer;
}

.other-settings {
  padding-top: 16px;
  margin-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.detail-tabs {
  margin-top: 16px;
}

.price-form,
.usage-form,
.points-form,
.description-form,
.validity-form {
  padding: 16px 0;
}

.usage-description {
  margin-bottom: 16px;
  font-style: italic;
  color: #666;
}

.usage-setting-container {
  display: flex;
  gap: 16px;
  align-items: center;
}

.dosage-settings {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.dosage-item {
  display: flex;
  gap: 12px;
  align-items: center;
}

.dosage-label {
  min-width: 120px;
  font-weight: 500;
}

.member-price-container {
  display: flex;
  gap: 8px;
  align-items: center;
}

.modal-footer {
  padding-top: 16px;
  margin-top: 24px;
  text-align: right;
  border-top: 1px solid #e8e8e8;
}
</style>
